package org.exteen.tag.core;

import java.net.MalformedURLException;
import java.net.URL;

import org.exteen.ExteenException;
import org.exteen.Script;
import org.exteen.exec.ExteenContext;
import org.exteen.exec.RootExteenContext;
import org.exteen.exec.Tag;
import org.exteen.output.ExteenStream;
import org.exteen.parser.Node;

public class IncludeTag extends Tag {

    public void doTag(ExteenContext ctx, ExteenStream stream) {
        Node node = ctx.getNode();
        if (node.getChildren().size() > 0) {
            throw new ExteenException("Include tag may not have a body");
        }
        Object uri = node.getAttributeValue("uri", ctx);
        if (uri == null) {
            throw new ExteenException(
                    "Include tag requires attribute 'uri' which is missing or null");
        }
        RootExteenContext rootCtx = (RootExteenContext) ctx.getParentOfType(RootExteenContext.class);
        if (rootCtx == null) {
            throw new ExteenException("Cannot include when root tag not found");
        }
        URL url = rootCtx.getScript().getSourceURL();
        if (url == null) {
            throw new ExteenException("Root script has no URL");
        }
        try {
            url = new URL(url, uri.toString());
        } catch (MalformedURLException e) {
            throw new ExteenException("Cannot build an URL of included script", e);
        }
        stream.flush();
        Script includedScript = null;
        try {
            includedScript = rootCtx.getScript().getParser().parse(url);
        } catch (Exception e) {
            throw new ExteenException("Cannot parse included script", e);
        }
        includedScript.doScript(ctx, stream);
        ctx.mergeToParent();
        stream.flush();
    }
}